/**
 * ${appData.type}.html加载后的回调，用于初始化应用
 * 
 * @param appData
 */
MApp.calendarInit = function(appData) {
	var divCalendar = $('#' + MApp.getDomId(appData, 'calendar'));
	
	// refresh日历event数据
	function refreshCalendar(subapp) {
		// 删除所有事件
		divCalendar.fullCalendar('removeEvents', function (event) {
			return !subapp || subapp == event.subapp;
		});
		// 获取视图时间范围内的所有事件
		var view = divCalendar.fullCalendar('getView');
		var subAppIds = [];
		$('[name=legend]:checked').each (function () {
			var subAppId = $(this).attr('data-app-id');
			if (subapp && subapp != subAppId) {
				return;
			}
			subAppIds.push(subAppId);
		});
		if (subAppIds.length == 0) {
			return;
		}
		var params = BigUtil.clone({
			start : view.start.format(),
			end : view.end.format(),
			subAppIds : subAppIds.join(',')
		}, appData);
		
		// 增加事件
		$.post('/meta/calendar/list', params, function (json) {
			if (json.success) {
				for (var i = 0; i < json.content.length; i ++) {
					var event = json.content[i];
					var color = $('[data-app-id="' + event.subapp + '"]').prev().css('color');
					event.backgroundColor = color;
					event.borderColor = color;
					divCalendar.fullCalendar('renderEvent', event);
				}
			}
		});
	}
	
	$('[name=legend]').click (function () {
		refreshCalendar();
	});
	
	var dateFormat = 'YYYY-MM-DD';
	var datetimeFormat = dateFormat + ' HH:mm:ss';
	
	// 将moment格式化为日期或者日期时间字符串
	function formatMoment (moment) {
		if (moment) {
			return moment.hasTime() ? moment.format(datetimeFormat) : moment.format(dateFormat);
		}
	}
	
	function submitSuccessAction (actions, subapp) {
		if (!BigUtil.containsValue (actions, 'keepTab')) {
			BigUtil.closeTab();
		}
		if (BigUtil.containsValue (actions, 'refreshTab')) {
			MApp.refreshTab();
		}
		if (BigUtil.containsValue (actions, 'refreshList')) {
			refreshCalendar(subapp);
		}
	}

	function setDate (createForm, date, dateStr) {
		var mkssj = createForm.find('[name$="_mkssj"]');
		// data-date-format="yyyy-mm-dd hh:ii:ss"
		var mkssjParent = mkssj.parents('[data-date-format]:first');
		mkssj.val(dateStr);
		if (mkssjParent.attr('data-date-format') == "yyyy-mm-dd hh:ii:ss") {
			if (!date.hasTime()) {
				mkssj.val(dateStr + ' 09:00:00');
			}
		} else if (mkssjParent.attr('data-date-format') == "yyyy-mm-dd") {
			if (date.hasTime()) {
				mkssj.val(dateStr.split(' ')[0]);
			}
		}
	}

	var date = new Date();
	var d = date.getDate(), m = date.getMonth(), y = date.getFullYear();
	var calendar = divCalendar.fullCalendar({
		locale: 'zh-cn',
		header : {
			left : 'prev,next today',
			center : 'title',
			right : 'month,agendaWeek,agendaDay'
		},
		editable : true,
		eventStartEditable : true,
		eventDurationEditable : true,
		// droppable : true, // this allows things to be dropped onto the calendar !!!
		// 点击视图上某个时间时，触发本方法，用于创建事件时设置时间
		dayClick : function( date, jsEvent, view, resourceObj) {
			var dateStr = formatMoment(date);
			var subAppData = {};
			// 查找应用对象input
			if ($('[name=legend]:checked:first').length == 0) {
				alert('请在左侧选择管理对象！');
				return;
			}
			subAppData = MApp.parseData($('[name=legend]:checked:first'));
			MApp.createDomprefix(subAppData);
			BigUtil.openTab({
				title : '新建' + subAppData.name,
				url : '/meta/' + subAppData.type + '/loadCreateForm',
				params : MApp.addRequestJson(subAppData, $(this)),
				fn : function (tabContent) {
					var createForm = tabContent.find('form:first');
					var mkssj = createForm.find('[name$="_mkssj"]');
					// data-date-format="yyyy-mm-dd hh:ii:ss"
					var mkssjParent = mkssj.parent().find('[data-date-format]');
					mkssj.val(dateStr);
					mkssjParent.attr('data-date', mkssj.val());
					mkssjParent.find('input').val(mkssj.val());
					if (mkssjParent.attr('data-date-format') == "yyyy-mm-dd hh:ii:ss") {
						if (!date.hasTime()) {
							mkssj.val(dateStr + ' 09:00:00');
							mkssjParent.attr('data-date', mkssj.val());
							mkssjParent.find('input').val(mkssj.val());
						}
					}
					MApp.initForm (subAppData, createForm, true);
						//.val(dateStr);
					createForm.find('button[data-app-buttontype=submitCreate]').click (function () {
						var mjssj = createForm.find('[name$="_mjssj"]');
						var minutes = createForm.find('[name$="_mfzs"]').val();
						if (date.hasTime()) {
							if (BigUtil.isEmpty (mjssj.val())) {
								if (!BigUtil.isEmpty (minutes)) {
									mjssj.val(date.add(minutes, 'minutes').format(datetimeFormat));
								}
							}
						} else if (mkssjParent.attr('data-date-format') == "yyyy-mm-dd hh:ii:ss") {
							if (BigUtil.isEmpty (mjssj.val())) {
								if (!BigUtil.isEmpty(minutes)) {
									mjssj.val(moment(mkssj.val(), datetimeFormat).add(minutes, 'minutes').format(datetimeFormat));
								}
							}
						}
						BigUtil.ajaxForm({
							form : createForm,
							url : '/meta/' + subAppData.type + '/create',
							params : subAppData,
							success : function (json) {
								if (json.success) {
									BigUtil.closeTab();
									// 刷新日历数据
									refreshCalendar(subAppData.id);
								} else {
									alert (json.msg);
								}
							}
						});
					});
				}
			});
		},
		// resize事件时，调用本方法，修改事件的结束时间
		eventResize : function( event, delta, revertFunc, jsEvent, ui, view ) {
			var data = {
				id : event.id,
				app : event.app,
				subapp : event.subapp,
				start : formatMoment(event.start),
				end : formatMoment(event.end)
			};
			$.post('/meta/calendar/end', data, function (json) {
				if (!json.success) {
					alert(json.msg);
					revertFunc();
				}
			});
		},
		eventDrop: function( event, delta, revertFunc, jsEvent, ui, view ) {
			var data = {
				id : event.id,
				app : event.app,
				subapp : event.subapp,
				start : formatMoment(event.start)
			};
			if (event.end) {
				data.end = formatMoment(event.end);
			}
			$.post('/meta/calendar/start', data, function (json) {
				if (!json.success) {
					alert(json.msg);
					revertFunc();
				}
			});
		},
		eventClick : function( event, jsEvent, view ) {
			var subAppData = MApp.parseData($('[data-app-id="' +event.subapp + '"][type="checkbox"]'));
			subAppData.selectedIds = event.id;
			BigUtil.openTab({
				title: "修改" + subAppData.name,
				url: '/meta/' + subAppData.type + '/loadUpdateForm',
				params: subAppData,
				fn: function (contentTab) {
					var updateForm = contentTab.find('form:first');
					MApp.initForm(subAppData, updateForm, false);
					// 提交按钮
					updateForm.find('button[data-app-buttontype=submitUpdate]').click(function () {
						BigUtil.ajaxForm({
							form : updateForm,
							url : '/meta/' + subAppData.type + '/update',
							params : subAppData,
							successFn : function (json) {
								BigUtil.closeTab();
								refreshCalendar(subAppData.id);
							}
						});
					});
					// requestJson按钮
					var btnRequestJson = updateForm.find('button[data-app-requesturl]');
					btnRequestJson.unbind();
					btnRequestJson.click (function (e) {
						if ($(this).hasClass('btn-danger') && !confirm ('该操作比较危险，确定要执行吗？')) {
							return;
						}
						var url = $(this).attr('data-app-requesturl');
						var actions = BigUtil.attr($(this), 'data-app-tabviewsubmit', 'refreshList');
						$.post(url, subAppData, function (json) {
							if (json.success) {
								submitSuccessAction(actions, subAppData.id);
							} else {
								alert(json.msg);
							}
						});
					});
				}
			});
		},
		viewRender : function( view, element ) {
			refreshCalendar();
		}
	});
	
	$('[name=legend]:first').click ();
	
};